package com.foftact.cave.controller;

import com.foftact.cave.Cave;
import com.foftact.cave.service.CaveService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 持仓与跟踪指数控制器
 */
@Controller
@RequestMapping("/cave")
public class CaveController {

    private static final Logger logger = LoggerFactory.getLogger(CaveController.class);

    @Autowired
    private CaveService caveService;

    /**
     * 跳转到持仓数据列表页面
     */
    @GetMapping("/list")
    public String listPage() {
        return "cave/list";
    }

    /**
     * 跳转到新增/编辑页面
     */
    @GetMapping("/edit")
    public String editPage(@RequestParam(value = "id", required = false) Long id, Model model) {
        if (id != null) {
            Cave cave = caveService.getCaveById(id);
            if (cave != null) {
                model.addAttribute("cave", cave);
            }
        }
        return "cave/edit";
    }

    /**
     * 异步获取持仓数据列表
     */
    @GetMapping("/dataList")
    @ResponseBody
    public List<Cave> getDataList() {
        logger.info("获取持仓数据列表");
        return caveService.getAllCaves();
    }

    /**
     * 根据关键字搜索持仓数据
     */
    @GetMapping("/search")
    @ResponseBody
    public List<Cave> search(@RequestParam("keyword") String keyword) {
        logger.info("搜索持仓数据，关键字：{}", keyword);
        return caveService.searchCavesByKeyword(keyword);
    }

    /**
     * 保存持仓数据（新增或更新）
     */
    @PostMapping("/save")
    @ResponseBody
    public Map<String, Object> save(@RequestBody Cave cave) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("保存持仓数据，代码：{}", cave.getCode());
            boolean success = caveService.saveCave(cave);
            if (success) {
                result.put("success", true);
                result.put("message", "保存成功");
            } else {
                result.put("success", false);
                result.put("message", "保存失败");
            }
        } catch (Exception e) {
            logger.error("保存持仓数据失败", e);
            result.put("success", false);
            result.put("message", "保存失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据代码删除持仓数据
     */
    @DeleteMapping("/delete/{code}")
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("code") String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("删除持仓数据，代码：{}", code);
            boolean success = caveService.deleteCaveByCode(code);
            if (success) {
                result.put("success", true);
                result.put("message", "删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            logger.error("删除持仓数据失败", e);
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据代码获取持仓详情
     */
    @GetMapping("/detail/{code}")
    @ResponseBody
    public Map<String, Object> getDetail(@PathVariable("code") String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            Cave cave = caveService.getCaveByCode(code);
            if (cave != null) {
                result.put("success", true);
                result.put("data", cave);
            } else {
                result.put("success", false);
                result.put("message", "未找到持仓数据");
            }
        } catch (Exception e) {
            logger.error("获取持仓详情失败：{}", code, e);
            result.put("success", false);
            result.put("message", "获取持仓详情失败：" + e.getMessage());
        }
        return result;
    }
}